package com.ruoyi.web.controller.system;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.CommunityBusinessTarget;
import com.ruoyi.system.service.ICommunityBusinessTargetService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import static com.ruoyi.common.utils.SecurityUtils.getUsername;
import static com.ruoyi.common.utils.SecurityUtils.getUserId;
import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import java.util.HashMap;
import java.util.Map;

/**
 * 小区业务目标Controller
 * 
 * @author alex
 * @date 2025-08-05
 */
@RestController
@RequestMapping("/system/target")
public class CommunityBusinessTargetController extends BaseController
{
    @Autowired
    private ICommunityBusinessTargetService communityBusinessTargetService;

    @Autowired
    private ISysDeptService deptService;

    /**
     * 查询小区业务目标列表
     */
    @PreAuthorize("@ss.hasPermi('system:target:list')")
    @GetMapping("/list")
    public TableDataInfo list(CommunityBusinessTarget communityBusinessTarget)
    {
        startPage();
        List<CommunityBusinessTarget> list = communityBusinessTargetService.selectCommunityBusinessTargetList(communityBusinessTarget);
        return getDataTable(list);
    }

    /**
     * 查询小区业务目标列表
     */
//    @PreAuthorize("@ss.hasPermi('system:target:list')")
    @PostMapping("/list")
    public AjaxResult serchList(@RequestBody CommunityBusinessTarget communityBusinessTarget)
    {
        // 1. 查找所有子部门
        SysDept sysDept = new SysDept();
        sysDept.setParentId(communityBusinessTarget.getDeptId());
        List<SysDept> sysDepts = deptService.selectDeptList(sysDept);

        // 2. 提取deptId列表
        List<Long> deptIds = sysDepts.stream()
                .map(SysDept::getDeptId)
                .collect(java.util.stream.Collectors.toList());

        // 3. 查询业务目标
        List<CommunityBusinessTarget> list = communityBusinessTargetService.selectCommunityBusinessTargetByDeptIds(deptIds);

        // 4. 过滤status=0
        List<CommunityBusinessTarget> filteredList = list.stream()
                .filter(item -> communityBusinessTarget.getStatus().equals(item.getStatus()))
                .collect(java.util.stream.Collectors.toList());

        // 5. 返回
        return AjaxResult.success(filteredList);
    }

    /**
     * 导出小区业务目标列表
     */
    @PreAuthorize("@ss.hasPermi('system:target:export')")
    @Log(title = "小区业务目标", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CommunityBusinessTarget communityBusinessTarget)
    {
        List<CommunityBusinessTarget> list = communityBusinessTargetService.selectCommunityBusinessTargetList(communityBusinessTarget);
        ExcelUtil<CommunityBusinessTarget> util = new ExcelUtil<CommunityBusinessTarget>(CommunityBusinessTarget.class);
        util.exportExcel(response, list, "小区业务目标数据");
    }

    /**
     * 获取小区业务目标详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:target:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(communityBusinessTargetService.selectCommunityBusinessTargetById(id));
    }

    /**
     * 新增小区业务目标
     */
    @PreAuthorize("@ss.hasPermi('system:target:add')")
    @Log(title = "小区业务目标", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CommunityBusinessTarget communityBusinessTarget)
    {
        return toAjax(communityBusinessTargetService.insertCommunityBusinessTarget(communityBusinessTarget));
    }

    /**
     * 修改小区业务目标
     */
    @PreAuthorize("@ss.hasPermi('system:target:edit')")
    @Log(title = "小区业务目标", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CommunityBusinessTarget communityBusinessTarget)
    {
        return toAjax(communityBusinessTargetService.updateCommunityBusinessTarget(communityBusinessTarget));
    }

    /**
     * 删除小区业务目标
     */
    @PreAuthorize("@ss.hasPermi('system:target:remove')")
    @Log(title = "小区业务目标", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(communityBusinessTargetService.deleteCommunityBusinessTargetByIds(ids));
    }

    @Log(title = "小区业务目标", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:target:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<CommunityBusinessTarget> util = new ExcelUtil<CommunityBusinessTarget>(CommunityBusinessTarget.class);
        List<CommunityBusinessTarget> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = communityBusinessTargetService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<CommunityBusinessTarget> util = new ExcelUtil<CommunityBusinessTarget>(CommunityBusinessTarget.class);
        util.importTemplateExcel(response, "小区目标数据");
    }

    @Log(title = "小区业务目标", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importTimeData")
    public AjaxResult importTimeData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<CommunityBusinessTarget> util = new ExcelUtil<CommunityBusinessTarget>(CommunityBusinessTarget.class);
        List<CommunityBusinessTarget> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = communityBusinessTargetService.importTimeUser(userList, updateSupport, operName);
        return success(message);
    }

    /**
     * 统计小区业务完成度
     */
    @PreAuthorize("@ss.hasPermi('system:target:edit')")
    @Log(title = "小区业务目标统计", businessType = BusinessType.UPDATE)
    @PostMapping("/countPesent")
    public AjaxResult countPesent(@RequestBody CommunityBusinessTarget communityBusinessTarget)
    {
        return AjaxResult.success(communityBusinessTargetService.countByRanking(communityBusinessTarget.getDeptId()));
    }

    /**
     * 获取当前登录用户的部门信息和下级小区列表
     */
    @PreAuthorize("@ss.hasPermi('system:target:list')")
    @GetMapping("/getUserDeptInfo")
    public AjaxResult getUserDeptInfo()
    {
        LoginUser loginUser = getLoginUser();
        Long deptId = loginUser.getUser().getDeptId();
        
        // 获取当前用户的部门信息
        SysDept currentDept = deptService.selectDeptById(deptId);
        if (currentDept == null) {
            return error("用户部门信息不存在");
        }
        
        Map<String, Object> result = new HashMap<>();
        
        // 如果当前部门是营业部级别，直接使用
        if (currentDept.getParentId() != null && currentDept.getParentId() != 0) {
            // 获取上级部门（区县分局）
            SysDept parentDept = deptService.selectDeptById(currentDept.getParentId());
            result.put("districtCompany", parentDept != null ? parentDept.getDeptName() : "");
            result.put("businessDepartment", currentDept.getDeptName());
            
            // 获取当前营业部下的所有小区
            SysDept queryDept = new SysDept();
            queryDept.setParentId(deptId);
            List<SysDept> communityList = deptService.selectDeptList(queryDept);
            result.put("communityList", communityList);
        } else {
            // 如果是区县分局级别，需要特殊处理
            result.put("districtCompany", currentDept.getDeptName());
            result.put("businessDepartment", "");
            result.put("communityList", new java.util.ArrayList<>());
        }
        
        return success(result);
    }

    /**
     * 根据状态查询小区列表（基于活动时间判断）
     * 
     * @param status 状态：0-已完成，1-计划开展
     * @return 小区业务目标集合
     */
//    @PreAuthorize("@ss.hasPermi('system:target:list')")
    @GetMapping("/listByStatus")
    public AjaxResult listByStatus(String status)
    {
        // 参数校验
        if (status == null || (!"0".equals(status) && !"1".equals(status))) {
            return error("状态参数错误，0为已完成，1为计划开展");
        }
        
        List<CommunityBusinessTarget> list = communityBusinessTargetService.selectCommunityBusinessTargetByStatus(status);
        return success(list);
    }

    /**
     * 查询未开展小区列表
     */
    @PreAuthorize("@ss.hasPermi('system:target:list')")
    @GetMapping("/unstartedCommunities")
    public AjaxResult getUnstartedCommunities()
    {
        List<SysDept> unstartedCommunities = communityBusinessTargetService.selectUnstartedCommunities();
        return success(unstartedCommunities);
    }

    /**
     * 获取小区营销服务活动开展情况统计数据
     */
    @PreAuthorize("@ss.hasPermi('system:target:list')")
    @GetMapping("/statistics")
    public AjaxResult getStatistics()
    {
        Map<String, Object> statistics = new HashMap<>();
        
        // 获取已完成小区数量
        List<CommunityBusinessTarget> completedList = communityBusinessTargetService.selectCommunityBusinessTargetByStatus("0");
        statistics.put("completed", completedList.size());
        
        // 获取计划开展小区数量
        List<CommunityBusinessTarget> plannedList = communityBusinessTargetService.selectCommunityBusinessTargetByStatus("1");
        statistics.put("planned", plannedList.size());
        
        // 获取未开展小区数量
        List<SysDept> unstartedList = communityBusinessTargetService.selectUnstartedCommunities();
        statistics.put("unstarted", unstartedList.size());
        
        return success(statistics);
    }
}
